package com.xinqi.modules.sys.menu.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.menu.convert.RoleMenuConvert;
import com.xinqi.modules.sys.menu.domain.RoleMenuEntity;
import com.xinqi.modules.sys.menu.dto.req.AddRoleMenuDTO;
import com.xinqi.modules.sys.menu.dto.req.RoleMenuCreateDTO;
import com.xinqi.modules.sys.menu.dto.req.RoleMenuDeleteDTO;
import com.xinqi.modules.sys.menu.dto.req.RoleMenuQueryDTO;
import com.xinqi.modules.sys.menu.dto.req.RoleMenuUpdateDTO;
import com.xinqi.modules.sys.menu.dto.rsp.MenuResultDTO;
import com.xinqi.modules.sys.menu.dto.rsp.RoleMenuResultDTO;
import com.xinqi.modules.sys.menu.manager.RoleMenuManager;
import com.xinqi.modules.sys.menu.service.RoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统角色菜单服务层实现
 *
 * @author: linkai
 * @date: 2023/04/01
 */
@Validated
@Service("roleMenuService")
@RequiredArgsConstructor
public class RoleMenuServiceImpl implements RoleMenuService {
    private final RoleMenuConvert roleMenuConvert;
    private final RoleMenuManager roleMenuManager;

    /**
     * 分页查询 系统角色菜单数据
     */
    @Override
    @DS("slaver")
    public PageInfo<RoleMenuResultDTO> page(Param pageable, RoleMenuQueryDTO query) {
        IPage<RoleMenuEntity> page = roleMenuManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, roleMenuConvert::convert);
    }

    /**
     * 查询 系统角色菜单数据
     */
    @Override
    public List<RoleMenuResultDTO> find(RoleMenuQueryDTO query) {
        return roleMenuManager.list(wrapper(query)).stream()
            .map(roleMenuConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<RoleMenuEntity> wrapper(RoleMenuQueryDTO query) {
        LambdaQueryWrapper<RoleMenuEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(RoleMenuEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 系统角色菜单数据
     */
    @Override
    public RoleMenuResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(roleMenuManager.findById(id)).map(roleMenuConvert::convert).orElse(null);
    }

    /**
     * 新增 系统角色菜单数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid RoleMenuCreateDTO dto) {
        RoleMenuEntity entity = roleMenuConvert.create(dto);
        roleMenuManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 系统角色菜单数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid RoleMenuUpdateDTO dto) {
        Optional.ofNullable(roleMenuManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        RoleMenuEntity entity = roleMenuConvert.update(dto);
        return roleMenuManager.updateById(entity);
    }

    /**
     * 根据id删除 系统角色菜单数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return roleMenuManager.removeById(id);
    }

    /**
     * 根据id删除 系统角色菜单数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(RoleMenuDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRoleMenu(AddRoleMenuDTO dto) {
        LambdaQueryWrapper<RoleMenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        // 删除
        roleMenuManager.remove(queryWrapper.eq(RoleMenuEntity::getRoleId, dto.getRoleId()));
        // 批量添加
        List<RoleMenuEntity> list = dto.getMenuIdList().stream().map(v -> {
            RoleMenuEntity syRoleMenu = new RoleMenuEntity();
            syRoleMenu.setRoleId(dto.getRoleId());
            syRoleMenu.setMenuId(v);
            return syRoleMenu;
        }).collect(Collectors.toList());
        roleMenuManager.saveBatch(list);
    }

    @Override
    public List<MenuResultDTO> findRoleMenu(Long roleId) {
        return roleMenuManager.findRoleMenu(roleId);
    }

}
